package cn.dxc.demo.service.impl;

import cn.dxc.demo.entity.User;
import cn.dxc.demo.mapper.UserMapper;
import cn.dxc.demo.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 通过用户名查找
     * @param user
     * @return
     */
    @Override
    public User findUserByParam(User user) {
        final QueryWrapper<User> query = Wrappers.query();
        query.eq("phone",user.getUsername()).or().eq("username",user.getUsername()).or().eq("email",user.getEmail());
        return userMapper.selectOne(query);
    }

    @Override
    public String insertUserForRegister(String phone,String password,String username,String companyName) {
        User user = new User();
        user.setPhone(phone);
        user.setPassword(password);
        user.setUsername(username);
        user.setCompanyName(companyName);
        QueryWrapper<User> query = Wrappers.query();
        query.eq("phone",phone);
        User userByQuery = userMapper.selectOne(query);
        if (userByQuery != null){
            return "500";
        }
        query = Wrappers.query();
        query.eq("username",username);
        userByQuery = userMapper.selectOne(query);
        if (userByQuery != null){

            return "405";
        }
        userMapper.insert(user);
        return "200";
    }

    @Override
    public Integer updateUserByPhone(User user) {
        final HashMap<String, Object> map = new HashMap<>();
        map.put("username",user.getUsername());
        map.put("phone",user.getPhone());
        map.put("companyName",user.getCompanyName());
        return userMapper.perfectInfo(map);
    }

    @Override
    public User findUserByPhone(String general) {
        final QueryWrapper<User> query = Wrappers.query();
        query.eq("phone",general).or().eq("email",general);
        return userMapper.selectOne(query);
    }

    @Override
    public Integer updateUserPassword(User user) {
        final HashMap<String, Object> map = new HashMap<>();
        map.put("phone",user.getPhone());
        map.put("email",user.getEmail());
        map.put("password",user.getPassword());
        return userMapper.alterPassword(map);
    }


}
